import { Button, Card, Divider, Form, Icon, Input, Modal, Table, message, Pagination } from "antd";
import React from "react";
import { connect } from 'dva';
import { formatMessage } from 'umi-plugin-react/locale';
import styles from "./index.less"
import moment from "moment";
import AddLanguageModel from "./addLanguageModel";
import UsingModelList from "./usingModelList";
import { languageModelList, languageModelRemove, languageModelTest, getLanguageDisabled, updateLanguageModelSort, getTenantDefaultModel, getTenantBaseInfo, setTenantDefaultModel } from "@/services/languageModel";
import UserSession from "@/UserSession";
class LanguageModel extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      current: 1,
      size: 10,
      total: 0,
      loading: false,
      list: [],
      selectedRowKeys: [],
      lastSelectedRowKey: undefined,
      rowSelectionDisabled: false,
      currentTenantId: 0,
    }
  }

  componentDidMount() {
    this.getList()
  }

  onRowSelectChange = (selectedRowKeys) => {
    const newSelectedRowKey = selectedRowKeys[0];
    const lastSelectedRowKey = this.state.lastSelectedRowKey;

    this.setState({
      selectedRowKeys,
      lastSelectedRowKey: newSelectedRowKey,
      rowSelectionDisabled: true
    });

    if (this.state.isAdmin) {
      updateLanguageModelSort({ "targetId": newSelectedRowKey, "cancelId": lastSelectedRowKey }).then(r => {
        if (r.code === 0) {
          this.setState({
            rowSelectionDisabled: false
          });
        }
      });
    } else {
      setTenantDefaultModel({ tenantId: this.state.currentTenantId, modelId: newSelectedRowKey }).then(r => {
        if (r.code === 0) {
          this.setState({
            rowSelectionDisabled: false
          });
        }
      });
    }

  }

  getList = () => {
    const { form: { getFieldsValue }, currentUser } = this.props;
    const { current, size } = this.state;
    this.setState({ loading: true }, async () => {
      this.setState({ isAdmin: currentUser.tenantId == "1" ? "admin" : undefined })
      let obj = { current, size, name: getFieldsValue().search, urlPrefix: currentUser.tenantId == "1" ? "admin" : undefined };
      const res = await languageModelList(obj)
      this.setState({ loading: false, list: res.records, total: res.total })
      this.setState({ currentTenantId: currentUser.tenantId })
      let idArray;
      if (this.state.isAdmin) {
        idArray = res.records.filter(record => record.sort === 0).map(record => record.id);
      } else {
        idArray = [];
        this.setState({rowSelectionDisabled: true});
        getTenantBaseInfo({ tenantId: currentUser.tenantId }).then(res => {
          if (res.defaultModelId !== null) {
            idArray = [res.defaultModelId];
            this.setState({ selectedRowKeys: idArray, lastSelectedRowKey: idArray[0], rowSelectionDisabled: false })
          }
        }).finally(() => {
          this.setState({ rowSelectionDisabled: false })
        });
      }

      this.setState({ selectedRowKeys: idArray, lastSelectedRowKey: idArray[0] })
    })
  }

  doSearch = (current, size) => {
    this.setState({ current, size }, () => this.getList())
  }

  openModal = () => {
    this.AddLanguageModel.initModal()
  }

  toEditPage = (row) => {
    const { history } = this.props;
    const currentUser = UserSession.getCurrentUser()
    history.push({
      pathname: currentUser.tenantId != '1' ? "/languageModel/edit/" + row.id : "/llmCenter/languageModel/edit/" + row.id,
      query: { isSys: row.isSys },
    });
  }

  openUseModel = (id) => {
    this.UsingModelList.initModal(id)
  }

  doTest = async row => {
    const res = await languageModelTest({ id: row.id, question: "你好" })
    message.info(res.message)
    this.getList()
  }

  renderRowClass = (record, index) => {
    if (record.type == 0) {
      return "defaultRowClass"
    }
  }

  removeConfirm = id => {
    Modal.confirm({
      title: formatMessage({ id: 'confirmDeleteTitle' }),
      content: formatMessage({ id: 'confirmDeleteContent' }),
      okText: formatMessage({ id: 'confirm' }),
      okType: "danger",
      cancelText: formatMessage({ id: 'cancel' }),
      onOk: () => {
        this.doRemove(id)
      }
    })
  }

  doRemove = async id => {
    const res = await languageModelRemove({ id })
    if (res.code == -1) { } else {
      message.info(res.message)
      this.getList();
    }
  }

  disabledLanguage = async (id, disabled) => {
    const res = await getLanguageDisabled({ id, disabled });
    console.log(res);
    if (res.code === 0) {
      message.success('操作成功')
      this.getList()
    }
  }

  render() {
    const { form: { getFieldDecorator }, currentUser } = this.props;
    const { current, size, total, list, loading } = this.state;
    const rowSelection = {
      type: 'radio',
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onRowSelectChange,
      disabled: true,
      getCheckboxProps: () => ({
        disabled: this.state.rowSelectionDisabled,
      }),
    };
    const columns = [
      {
        title: formatMessage({ id: 'modelName' }),
        dataIndex: "name",
        width: 200
      },
      {
        title: formatMessage({ id: 'modelId' }),
        dataIndex: "modelName",
        width: 200
      },
      {
        title: formatMessage({ id: 'createTime' }),
        dataIndex: "createTime",
        width: 200,
        render: time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title: formatMessage({ id: 'description' }),
        dataIndex: "comment",
        width: 300
      },
      {
        title: formatMessage({ id: 'modelType' }),
        dataIndex: "modelType",
        width: 200,
        render: text => {
          let label = "";
          switch (text) {
            case '1':
              label = formatMessage({ id: 'internalModel' })
              break;
            case '2':
              label = formatMessage({ id: 'externalModel' })
              break;
          };
          return label;
        }
      },
    ];
    if (currentUser.tenantId != '1') {
      columns.push(
        {
          title: formatMessage({ id: 'modelOwner' }),
          dataIndex: "isSys",
          width: 200,
          render: text => {
            if (text) {
              return formatMessage({ id: 'systemAllocated' });
            } else {
              return formatMessage({ id: 'selfBuilt' });
            }
          }
        },
      )
    };
    columns.push(
      {
        title: formatMessage({ id: 'testStatus' }),
        dataIndex: "status",
        width: 150,
        render: (status, row) => {
          let text = '';
          switch (status) {
            case 0:
              text = formatMessage({ id: 'notTested' });
              break;
            case 1:
              text = formatMessage({ id: 'notPassed' });
              break;
            case 2:
              text = formatMessage({ id: 'passed' });
              break;
          };

          return (
            <div>
              <Icon type="sync" style={{ marginRight: 10, cursor: "pointer" }} onClick={() => this.doTest(row)} />
              <span style={{ color: status == 1 ? 'red' : '' }}>{text}</span>
            </div>
          )
        }
      },
    );
    if (currentUser.tenantId != '1') {
      columns.push(
        {
          title: formatMessage({ id: 'usageStatus' }),
          dataIndex: "used",
          width: 150,
          align: 'center',
          render: (used, row) => {
            return used ? (
              <div className={styles.useStyle} onClick={() => this.openUseModel(row.id)}>
                <span className={styles.roundOut}><span className={styles.roundIn}></span></span>
                <span>{formatMessage({ id: 'inUse' })}</span>
              </div>
            ) : '-'
          }
        },
      )
    };
    columns.push(
      {
        title: formatMessage({ id: 'operation' }),
        width: 200,
        fixed: "right",
        render: (text, row) => {
          return (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: '16px' }}>
              {row.isSys ? (
                <span style={{ color: '#3E5BFF', cursor: "pointer" }} onClick={() => this.toEditPage(row)}>{formatMessage({ id: 'view' })}</span>
              ) : (
                <span style={{ color: '#3E5BFF', cursor: "pointer" }} onClick={() => this.toEditPage(row)}>{formatMessage({ id: 'edit' })}</span>
              )}
              {row.type == 0 || row.isSys ? '' : (
                <span style={{ color: '#D54941', cursor: "pointer" }} onClick={() => this.removeConfirm(row.id)}>{formatMessage({ id: 'delete' })}</span>
              )}
              {currentUser.tenantId == '1' ? (
                <>
                  {row.disabled ? <span style={{ color: '#3E5BFF', cursor: "pointer" }} onClick={() => this.disabledLanguage(row.id, false)}>{formatMessage({ id: 'enable' })}</span> : null}
                  {!row.disabled ? <span style={{ color: '#faad14', cursor: "pointer" }} onClick={() => this.disabledLanguage(row.id, true)}>{formatMessage({ id: 'disable' })}</span> : null}
                </>
              ) : null}
            </span>
          )
        }
      }
    )

    return (
      <Card bordered={false} style={{ height: '100%' }} bodyStyle={{ paddingBottom: 16 }}>
        <div className={styles.top}>
          <div>
            <Form layout="inline">
              <Form.Item>
                {getFieldDecorator("search")(
                  <Input.Search placeholder={formatMessage({ id: 'enterModelName' })} onSearch={() => this.doSearch(1, size)} />
                )}
              </Form.Item>
              <Form.Item>
                <Button type="primary" onClick={() => this.doSearch(1, size)}>{formatMessage({ id: 'search' })}</Button>
              </Form.Item>
            </Form>
          </div>
          <Button type="primary" onClick={this.openModal}>{formatMessage({ id: 'add' })}</Button>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={list}
          loading={loading}
          scroll={{ x: "auto" }}
          rowKey={'id'}
          rowClassName={this.renderRowClass}
          pagination={false}
        />
        {total > 10 ? (
          <Pagination
            style={{ textAlign: 'right', marginTop: 16 }}
            onChange={this.doSearch}
            current={current}
            pageSize={10}
            total={total}
            showQuickJumper={true} locale={{ jump_to: formatMessage({ id: 'goTo' }) }}
          />
        ) : null}

        <AddLanguageModel onRef={ref => this.AddLanguageModel = ref} refreshParent={() => this.doSearch(current, size)} />
        <UsingModelList onRef={ref => this.UsingModelList = ref} />
      </Card>
    )
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(LanguageModel))